package com.example.myapplication;

import android.content.Context;
import android.graphics.Rect;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class Detect {
    static {
        try {
            System.loadLibrary("eyeLibrary");

        } catch (Throwable e) {
            Log.d("syshen", "加载eye库异常 ：" + e.toString());

        }
    }

    public boolean init(Context mContext) {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "mnn";
        String modelPath = copyModel2SD(mContext, "model", path);

        String face_path = modelPath + File.separator + "RFB";
        String landmark_path = modelPath + File.separator + "FaceLandmark_tf";
        String eyesegment_path = modelPath + File.separator + "eyeSegmentation";
        boolean ret = initDetector(face_path, landmark_path, eyesegment_path, 1);
        if (!ret) {
            return false;
        }
        return true;
    }

    public native boolean initDetector(String mnnPath, String landmark_mnn_path, String eyesegment_mnn_path, int numThread);

    public native float[] detectyuv(byte[] yuv, int width, int height);

    public native float[] detectpath(String path);

    public native float[] detectbyte(byte [] img, int width, int height);

    private String copyModel2SD(Context mContext, String model, String path) {
        String modelPath = path + File.separator + model;

        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }

        File file2 = new File(modelPath);
        if (!file2.exists()) {
            file2.mkdirs();
        }

        try {
            copyAssets(mContext, model, modelPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return modelPath;
    }

    public static void copyAssets(Context mContext, String oldPath, String newPath) throws IOException {
        String fileNames[] = mContext.getAssets().list(oldPath);
        if (fileNames.length > 0) {
            File file = new File(newPath);
            file.mkdirs();
            for (String fileName : fileNames) {
                copyAssets(mContext, oldPath + File.separator + fileName, newPath + File.separator + fileName);
            }
        } else {
            InputStream is = mContext.getAssets().open(oldPath);
            FileOutputStream fos = new FileOutputStream(new File(newPath));
            byte[] buffer = new byte[1024];
            int byteCount = 0;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            is.close();
            fos.close();
        }
    }
}
